package com.example.product_practices.controller.login;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.product_practices.config.SendEmail;
import com.example.product_practices.config.SmsCom;
import com.example.product_practices.constant.AuthServerConstant;
import com.example.product_practices.domain.User;
import com.example.product_practices.exception.BizCodeEnume;
import com.example.product_practices.service.IUserService;
import com.example.product_practices.vo.UserLoginVo;
import com.example.product_practices.vo.UserRegister;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xin.altitude.cms.common.entity.AjaxResult;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

//import static com.hzx.common.constant.AuthServerConstant.LOGIN_USER;

@RestController
@CrossOrigin
public class loginController {
    @Autowired
    SmsCom smsCom;

    @Autowired(required = false)
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    IUserService userService;

    /**
     * 邮箱验证码接口
     * @param email
     * @param length
     * @return
     */
    @ResponseBody
    @GetMapping("/sendcode")
    public AjaxResult sendemail(@RequestParam("email") String email, @RequestParam("length")int length){
        if(!email.contains("@")||email.split("@")[0].length()<2||!email.split("@")[1].contains(".com")){
            return AjaxResult.error(BizCodeEnume.SMS_EMAIl_EXCEPTION.getCode(), BizCodeEnume.SMS_EMAIl_EXCEPTION.getMsg());
        }
        if (redisconfig(email))
            return AjaxResult.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
        SendEmail sendEmail=new SendEmail();
        //设置要发送的邮箱"2830768536@qq.com"
        sendEmail.setReceiveMailAccount(email);
        //创建10位发验证码
        Random random=new Random();
        String str="";
        for(int i=0;i<length;i++) {
            int n=random.nextInt(10);
            str+=n;
        }
        sendEmail.setInfo(str);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+email,str+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        try {
            sendEmail.Send();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    private boolean redisconfig(@RequestParam("email") String email) {
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);
        if (!StringUtils.isEmpty(s)){
            long l = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis()-l<60000){
                return true;
            }
        }
        return false;
    }

    /**
     *手机验证码接口
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sendphonecode")
    public AjaxResult sendphone(@RequestParam("phone")String phone){

        if (redisconfig(phone))
            return AjaxResult.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
        //创建10位发验证码
        Random random=new Random();
        String str="";
        for(int i=0;i<4;i++) {
            int n=random.nextInt(10);
            str+=n;
        }
        smsCom.phone(phone,str);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,str+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

    //TODO 登录和注册逻辑(没修改完)
    @PostMapping("/regist")
//    public AjaxResult regist(@Valid UserRegister userRegister, BindingResult result,
//                         RedirectAttributes redirectAttributes) {
    public AjaxResult regist(@RequestBody UserRegister userRegister, BindingResult result,
                             RedirectAttributes redirectAttributes) {
        /*if (result.hasErrors()) {
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, fieldError -> fieldError.getDefaultMessage()));
//            model.addAttribute("errors",collect);
            redirectAttributes.addFlashAttribute("errors",collect);
            System.out.println("1");
            return AjaxResult.error();

        }*/
        String code = userRegister.getCode();
        System.out.println("userauth:"+code);
//        String redisCode="1234";
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegister.getEmail());
//        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + "1023118868@qq.com");
        System.out.println("rediscode"+redisCode);
        if (!StringUtils.isEmpty(redisCode)) {
            if (code.equals(redisCode.split("_")[0])) {
                userService.regist(userRegister);
                return AjaxResult.success();
            }else {
                Map<String, String> collect = new HashMap<>();
                collect.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",collect);
                System.out.println("2");
                return AjaxResult.success();
            }
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            System.out.println("3");
            return AjaxResult.success();
        }
    }

    @PostMapping("/loginbypassword")
    public AjaxResult loginbypassword(@RequestBody UserLoginVo userLoginVo,RedirectAttributes redirectAttributes, HttpSession session){
        System.out.println(userLoginVo);
        User data  = userService.login(userLoginVo);
        System.out.println(data);
        if(data==null){
            Map<String,String>errors=new HashMap<>();
            errors.put("msg",BizCodeEnume.LOGINACCT_PASSWORD_EXCEPTION.getMsg());
            redirectAttributes.addFlashAttribute("errors",errors);
            return AjaxResult.error(null);
        }

//        session.setAttribute(LOGIN_USER,data);
        System.out.println(data.getAuth());
        return AjaxResult.success(data);
    }

    @PostMapping("/loginbycode")
    public String loginbycode(UserLoginVo userLoginVo,RedirectAttributes redirectAttributes, HttpSession session,String code){

        int count = userService.count(new QueryWrapper<User>().eq("phone", userLoginVo.getLoginacct()));
        if (count==0){
            Map<String, String> collect = new HashMap<>();
            collect.put("phone","手机号错误");
            redirectAttributes.addFlashAttribute("errors",collect);
            return "redirect:http://localhost:8080/doc.html";
        }
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userLoginVo.getLoginacct());
        if (!StringUtils.isEmpty(redisCode)&&code.equals(redisCode.split("_")[0])) {
                return "redirect:http://localhost:8080/doc.html";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://localhost:8080/doc.html";
        }
//            session.setAttribute(LOGIN_USER,data);
        //TODO
    }


//    @GetMapping("/login.html")
//    public String loginPage(HttpSession session){
//        Object attribute = session.getAttribute(LOGIN_USER);
//        if (attribute == null) {
//            return "redirect:http://localhost:8080/doc.html";
//        }else {
//            //TODO
//            return "redirect:http://localhost:8080/doc.html";
//        }
//
//    }

}
